package com.s7.app.delegate.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;

import com.s7.app.CompatFragment;
import com.s7.app.delegate.FDelegate;

import java.lang.reflect.ParameterizedType;

/**
 * Created by Administrator on 2017/5/6.
 * 视图被代理 Fragment
 */
public abstract class FragmentPresenter<T extends FDelegate> extends CompatFragment {

    public T viewDelegate;

    /**
     * 获取代理视图
     * @param savedInstanceState
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ParameterizedType pt = (ParameterizedType) this.getClass()
                .getGenericSuperclass();
        Class<T> clazz = (Class<T>) pt.getActualTypeArguments()[0];

        try {
            viewDelegate = clazz.newInstance();
        } catch (Fragment.InstantiationException e) {
            throw new RuntimeException("create IDelegate error");
        } catch (IllegalAccessException e) {
            throw new RuntimeException("create IDelegate error");
        } catch (java.lang.InstantiationException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置代理视图
     * @param savedInstanceState
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        viewDelegate.onCreateView(inflater, container, savedInstanceState);
        return viewDelegate.getRootView();
    }

    /**
     * 初始化代理视图的控件
     * @param view
     * @param savedInstanceState
     */
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewDelegate.initWidget();
    }

    /**
     * 设置菜单代理视图
     * @param menu
     * @return
     */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        if (viewDelegate.getOptionsMenuId() != 0) {
            inflater.inflate(viewDelegate.getOptionsMenuId(), menu);
        }
    }

    /**
     * 销毁代理视图
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        viewDelegate = null;
    }


}
